package com.ryze.common.dubbo.filter;

import com.alibaba.fastjson.JSON;
import com.ryze.common.dubbo.project.ProjectEnvUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.Map;

@Slf4j
@Activate(group = {CommonConstants.CONSUMER})
public class ConsumerRpcContextFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Map<String,Object> params = RyzeRpcContext.getContext().getContextParams();
        log.debug("set rpc context:", JSON.toJSONString(params));
        params.forEach((k,v) -> RpcContext.getContext().setAttachment(k,v));

        if(StringUtils.isBlank(RpcContext.getContext().getAttachment(RyzeRpcContext.K_PROJECTGROUP))){
            if(ProjectEnvUtils.isProjectEnv()) {
                RpcContext.getContext().setAttachment(RyzeRpcContext.K_PROJECTGROUP, ProjectEnvUtils.getGroup());
            }
        }
        return invoker.invoke(invocation);
    }
}
